<template>
  <div class="manual-matching-container">
    <div class="page-header">
      <div class="page-title">漏洞手动匹配</div>
      <div class="page-actions">
        <el-button icon="Refresh" @click="resetForm">重置</el-button>
        <el-button type="primary" icon="Search" @click="handleSearchVulnerability">搜索漏洞</el-button>
      </div>
    </div>

    <!-- 匹配表单 -->
    <el-card class="matching-form-card">
      <template #header>
        <div class="card-header">匹配条件</div>
      </template>
      <el-form :model="matchingForm" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="资产信息">
              <el-select 
                v-model="matchingForm.assetId" 
                placeholder="选择要匹配的资产" 
                filterable
                clearable
                style="width: 100%">
                <el-option 
                  v-for="item in assetOptions" 
                  :key="item.id" 
                  :label="item.name" 
                  :value="item.id">
                  <span>{{ item.name }}</span>
                  <span style="color: var(--text-color-secondary); margin-left: 15px">{{ item.ip }}</span>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="漏洞类型">
              <el-select 
                v-model="matchingForm.vulnType" 
                placeholder="选择漏洞类型" 
                clearable
                style="width: 100%">
                <el-option 
                  v-for="item in vulnTypeOptions" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="风险等级">
              <el-select 
                v-model="matchingForm.riskLevel" 
                placeholder="选择风险等级" 
                clearable
                style="width: 100%">
                <el-option 
                  v-for="item in riskLevelOptions" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value">
                  <el-tag :type="getTagType(item.value)" size="small">{{ item.label }}</el-tag>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="CVE 编号">
              <el-input v-model="matchingForm.cveId" placeholder="请输入CVE编号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发布日期">
              <el-date-picker
                v-model="matchingForm.publishDateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="关键词">
              <el-input v-model="matchingForm.keyword" placeholder="请输入漏洞名称/关键词" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 搜索结果 -->
    <div class="search-result-container">
      <div class="result-header">
        <div class="result-title">可匹配漏洞</div>
        <div class="result-actions">
          <el-button type="primary" @click="handleBatchMatch" :disabled="!selectedVulnerabilities.length">
            批量匹配 ({{ selectedVulnerabilities.length }})
          </el-button>
        </div>
      </div>
      
      <el-table 
        :data="vulnerabilityList" 
        border 
        style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="漏洞ID" min-width="150" />
        <el-table-column prop="name" label="漏洞名称" min-width="180" show-overflow-tooltip />
        <el-table-column prop="type" label="漏洞类型" width="120" />
        <el-table-column prop="level" label="风险等级" width="100">
          <template #default="{ row }">
            <el-tag :type="getTagType(row.level)">{{ formatLevel(row.level) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="cveId" label="CVE编号" width="150" />
        <el-table-column prop="publishDate" label="发布日期" width="120" />
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button type="primary" link icon="View" @click="handleViewDetails(row)">查看详情</el-button>
            <el-button type="success" link icon="Link" @click="handleMatch(row)">匹配</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
    
    <!-- 匹配详情对话框 -->
    <el-dialog
      v-model="matchDialogVisible"
      title="漏洞匹配详情"
      width="700px">
      <el-form :model="matchForm" label-width="100px">
        <el-form-item label="漏洞ID">
          <el-input v-model="matchForm.id" disabled />
        </el-form-item>
        <el-form-item label="漏洞名称">
          <el-input v-model="matchForm.name" disabled />
        </el-form-item>
        <el-form-item label="匹配资产">
          <el-select 
            v-model="matchForm.assetId" 
            placeholder="选择要匹配的资产" 
            filterable
            style="width: 100%">
            <el-option 
              v-for="item in assetOptions" 
              :key="item.id" 
              :label="item.name" 
              :value="item.id">
              <span>{{ item.name }}</span>
              <span style="color: var(--text-color-secondary); margin-left: 15px">{{ item.ip }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="匹配依据">
          <el-input 
            v-model="matchForm.matchReason" 
            type="textarea" 
            rows="3"
            placeholder="请输入匹配该漏洞的原因或依据" />
        </el-form-item>
        <el-form-item label="匹配分值">
          <el-slider
            v-model="matchForm.confidence"
            :min="0"
            :max="100"
            :marks="{
              0: '0',
              25: '25',
              50: '50',
              75: '75',
              100: '100'
            }"
            show-stops />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="matchDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmMatch">确认匹配</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 分页数据
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索表单
const matchingForm = reactive({
  assetId: '',
  vulnType: '',
  riskLevel: '',
  cveId: '',
  publishDateRange: '',
  keyword: ''
})

// 漏洞列表和选中项
const vulnerabilityList = ref([])
const selectedVulnerabilities = ref([])

// 对话框状态
const matchDialogVisible = ref(false)
const matchForm = reactive({
  id: '',
  name: '',
  assetId: '',
  matchReason: '',
  confidence: 50
})

// 下拉选项
const assetOptions = ref([
  { id: '1', name: '内部Web服务器', ip: '192.168.1.100' },
  { id: '2', name: '数据库服务器', ip: '192.168.1.101' },
  { id: '3', name: '文件服务器', ip: '192.168.1.102' },
  { id: '4', name: '测试服务器', ip: '192.168.2.100' },
  { id: '5', name: '生产环境服务器', ip: '10.10.10.50' }
])

const vulnTypeOptions = ref([
  { value: 'injection', label: '注入型漏洞' },
  { value: 'xss', label: '跨站脚本' },
  { value: 'csrf', label: '跨站请求伪造' },
  { value: 'fileUpload', label: '文件上传' },
  { value: 'privilege', label: '权限提升' },
  { value: 'dos', label: '拒绝服务' },
  { value: 'overflow', label: '缓冲区溢出' },
  { value: 'other', label: '其他漏洞' }
])

const riskLevelOptions = ref([
  { value: 'critical', label: '严重' },
  { value: 'high', label: '高危' },
  { value: 'medium', label: '中危' },
  { value: 'low', label: '低危' }
])

// 格式化危害等级
const formatLevel = (level) => {
  const levelMap = {
    'critical': '严重',
    'high': '高危',
    'medium': '中危',
    'low': '低危'
  }
  return levelMap[level] || level
}

// 获取标签类型
const getTagType = (level) => {
  const typeMap = {
    'critical': 'danger',
    'high': 'warning',
    'medium': '',
    'low': 'info'
  }
  return typeMap[level] || ''
}

// 处理分页变化
const handleSizeChange = (val) => {
  pageSize.value = val
  loadVulnerabilityList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadVulnerabilityList()
}

// 重置表单
const resetForm = () => {
  Object.keys(matchingForm).forEach(key => {
    matchingForm[key] = ''
  })
  loadVulnerabilityList()
}

// 处理搜索漏洞
const handleSearchVulnerability = () => {
  currentPage.value = 1
  loadVulnerabilityList()
}

// 加载漏洞列表
const loadVulnerabilityList = () => {
  // 模拟API调用
  setTimeout(() => {
    const mockData = []
    const typeLabels = vulnTypeOptions.value.reduce((acc, item) => {
      acc[item.value] = item.label
      return acc
    }, {})
    
    for (let i = 1; i <= 30; i++) {
      const type = vulnTypeOptions.value[Math.floor(Math.random() * vulnTypeOptions.value.length)].value
      const level = riskLevelOptions.value[Math.floor(Math.random() * riskLevelOptions.value.length)].value
      const year = 2020 + Math.floor(Math.random() * 4)
      const month = Math.floor(Math.random() * 12) + 1
      const day = Math.floor(Math.random() * 28) + 1
      
      mockData.push({
        id: `VLN-${2023000 + i}`,
        name: `${typeLabels[type]}样本-${i}`,
        type: typeLabels[type],
        level,
        cveId: `CVE-${year}-${10000 + Math.floor(Math.random() * 9999)}`,
        publishDate: `${year}-${month.toString().padStart(2, '0')}-${day.toString().padStart(2, '0')}`,
        description: '这是一个示例漏洞描述，用于测试漏洞匹配功能。'
      })
    }
    
    // 过滤逻辑
    let filteredData = [...mockData]
    
    if (matchingForm.vulnType) {
      filteredData = filteredData.filter(item => 
        item.type === typeLabels[matchingForm.vulnType]
      )
    }
    
    if (matchingForm.riskLevel) {
      filteredData = filteredData.filter(item => 
        item.level === matchingForm.riskLevel
      )
    }
    
    if (matchingForm.cveId) {
      filteredData = filteredData.filter(item => 
        item.cveId.toLowerCase().includes(matchingForm.cveId.toLowerCase())
      )
    }
    
    if (matchingForm.keyword) {
      filteredData = filteredData.filter(item => 
        item.name.toLowerCase().includes(matchingForm.keyword.toLowerCase()) ||
        item.description.toLowerCase().includes(matchingForm.keyword.toLowerCase())
      )
    }
    
    if (matchingForm.publishDateRange && matchingForm.publishDateRange.length === 2) {
      const startDate = new Date(matchingForm.publishDateRange[0])
      const endDate = new Date(matchingForm.publishDateRange[1])
      
      filteredData = filteredData.filter(item => {
        const publishDate = new Date(item.publishDate)
        return publishDate >= startDate && publishDate <= endDate
      })
    }
    
    total.value = filteredData.length
    
    // 分页
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    vulnerabilityList.value = filteredData.slice(start, end)
    
  }, 500)
}

// 处理表格选择变化
const handleSelectionChange = (val) => {
  selectedVulnerabilities.value = val
}

// 查看详情
const handleViewDetails = (row) => {
  console.log('查看漏洞详情:', row)
  ElMessage.info(`正在查看漏洞 ${row.id} 的详细信息`)
}

// 处理单个漏洞匹配
const handleMatch = (row) => {
  matchForm.id = row.id
  matchForm.name = row.name
  matchForm.assetId = matchingForm.assetId || ''
  matchForm.matchReason = ''
  matchForm.confidence = 50
  matchDialogVisible.value = true
}

// 处理批量匹配
const handleBatchMatch = () => {
  if (!matchingForm.assetId) {
    ElMessage.warning('请先选择要匹配的资产')
    return
  }
  
  ElMessageBox.confirm(
    `确定要将选中的 ${selectedVulnerabilities.value.length} 个漏洞匹配到选定资产吗？`,
    '批量匹配确认',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 模拟批量匹配成功
    ElMessage.success(`已成功匹配 ${selectedVulnerabilities.value.length} 个漏洞到指定资产`)
    selectedVulnerabilities.value = []
  }).catch(() => {
    // 取消操作
  })
}

// 确认匹配
const confirmMatch = () => {
  if (!matchForm.assetId) {
    ElMessage.warning('请选择要匹配的资产')
    return
  }
  
  if (!matchForm.matchReason) {
    ElMessage.warning('请输入匹配依据')
    return
  }
  
  // 模拟匹配成功
  ElMessage.success(`漏洞 ${matchForm.id} 已成功匹配到资产`)
  matchDialogVisible.value = false
}

// 初始化
onMounted(() => {
  loadVulnerabilityList()
})
</script>

<style lang="scss" scoped>
.manual-matching-container {
  padding: 20px;
  
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    .page-title {
      font-size: 20px;
      font-weight: bold;
      color: var(--text-color);
    }
    
    .page-actions {
      display: flex;
      gap: 10px;
    }
  }
  
  .matching-form-card {
    margin-bottom: 20px;
    
    .card-header {
      font-weight: bold;
    }
  }
  
  .search-result-container {
    margin-top: 20px;
    
    .result-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      
      .result-title {
        font-size: 16px;
        font-weight: bold;
      }
    }
    
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style> 